#!/bin/bash
if [ $# -ne 3 ]; then
    echo "usage: $0 <METHOD> <URI> <JSON_FILE>" >&2
    echo "    i.e.: $0 POST /v1/user/update update.json" >&2
    exit 1
fi

# init param
METHOD=$(echo "$1" | tr '[:lower:]' '[:upper:]')
URI="$2"
JSON_FILE="$3"

# Check METHOD
case "$METHOD" in
    GET|POST|PUT|DELETE|PATCH|HEAD|OPTIONS) ;;
    *)
        echo "[ERROR]: $METHOD error" >&2
        exit 1
        ;;
esac

# check param_02: URI
# check param_03: data.json file
if [ ! -f "$JSON_FILE" ]; then
    JSON_DATA=""
else
    JSON_DATA=$(jq -c . $JSON_FILE 2>/dev/null)
    if [ $? -ne 0 ]; then
        echo "[ERROR]: $JSON_FILE unvalid" >&2
        exit 1
    fi
fi


# Read token from file
if [ ! -f token.txt ]; then
    echo "[ERROR]: token.txt not found!" >&2
    exit 1
fi
TOKEN=$(cat token.txt | xargs)
if [ -z "$TOKEN" ]; then
    echo "[ERROR]: token.txt is empty!" >&2
    exit 1
fi
# Build curl command
CURL_ARGS=(
    curl
    --request "$METHOD"
    --url "http://127.0.0.1:80$URI"
    --header "Accept: */*"
    --header "Accept-Encoding: gzip, deflate, br"
    --header "Access-Token: $TOKEN"
    --header "Connection: keep-alive"
    --header "User-Agent: PostmanRuntime-ApipostRuntime/1.1.0"
)

# Add Content-Type and data only if needed
if [ -n "$JSON_DATA" ]; then
    CURL_ARGS+=(
        --header "Content-Type: application/json"
        --data "$JSON_DATA"
    )
fi

# Execute
if [ -n "$JSON_DATA" ]; then
	echo "$JSON_DATA"
else
	echo "(null)"
fi
"${CURL_ARGS[@]}"
echo 
echo 
